<?php

class BannerController extends Controller
{
	/**
    * Set layout
   */
   public $layout = '//layouts/cms/main';
   
   public function filters()
	{
		return array(
         'accessControl', // perform access control for CRUD operations
      );
	}
   
   public function accessRules(){
      $rights = Role::getRights($this->id);
      return $rights;
   }
   
   /**
	 * Check login all action
	 */
   public function beforeAction($action){
      if(is_null(Yii::app()->user->id))
         $this->redirect('/admin/default/login');
      else
         return true;
   }
   
   public function actionIndex()
	{
	   $criteria = new CDbCriteria();
      $criteria->offset = 0;
      $criteria->limit = 4;
      $criteria->group = 'ban_position';
      $criteria->order = 'ban_id DESC'; 
      $models = Banner::model()->findAll($criteria);
		$this->render('index',array(
         'models' => $models,
      ));
	}
   
   public function actionCreate(){
      $model = new Banner();
      $message =  '';
      $PostImage = new PostImage();
      $session_user = md5(time());
      Yii::app()->session['session_user'] = $session_user;
      $action_user = Yii::app()->request->getParam('action_user',''); // Biến xác định user ấn apply hay save
      $message = '';
      if(isset($_POST['Banner'])){
         $model->attributes = $_POST['Banner'];
         if($model->validate()){
            //Upload image
            $images = CUploadedFile::getInstancesByName('Banners');
            if(isset($images) && count($images)> 0)
               foreach ($images as $image=>$pic){
                  //Rename file image
                  $fileName = date('YmdHis',time());
                  switch($pic->type){
                     case 'image/jpeg':
                        $fileName .= '.jpg';
                        break;
                     case 'image/png':
                        $fileName .='.png';
                        break;
                     default:
                        $fileName .='.gif';
                        break;
                  }
                  $path_to_upload = Yii::getPathOfAlias('webroot').'/uploads/pictures/banners/';
                  if($pic->saveAs($path_to_upload.$fileName,0777)){
                     $model->ban_image = $fileName;
                     if($model->save()){
                        $message = "Tạo thành công";   
                     }
                  } 
                             
               }
         }
      }
      $this->pageTitle = 'Tạo banner';
      $this->layout = '//layouts/cms/create';
      $this->render('create',array(
         'model' => $model,
         'message' => $message,
      ));
   }
   
   public function actionEdit($id){
      $model = Banner::model()->findByPk($id);
      $message =  '';
      $PostImage = new PostImage();
      $session_user = md5(time());
      Yii::app()->session['session_user'] = $session_user;
      $action_user = Yii::app()->request->getParam('action_user',''); // Biến xác định user ấn apply hay save
      $message = '';
      if(isset($_POST['Banner'])){
         $model->attributes = $_POST['Banner'];
         if($model->validate()){
            //Upload image
            $images = CUploadedFile::getInstancesByName('Banners');
            if(isset($images) && count($images)> 0)
               foreach ($images as $image=>$pic){
                  //Rename file image
                  $fileName = date('YmdHis',time());
                  switch($pic->type){
                     case 'image/jpeg':
                        $fileName .= '.jpg';
                        break;
                     case 'image/png':
                        $fileName .='.png';
                        break;
                     default:
                        $fileName .='.gif';
                        break;
                  }
                  $path_to_upload = Yii::getPathOfAlias('webroot').'/uploads/pictures/banners/';
                  if($pic->saveAs($path_to_upload.$fileName,0777)){
                     $model->ban_image = $fileName;
                     if($model->save()){
                        $message = "Tạo thành công";   
                     }
                  } 
                             
               }
         }
      }
      $this->pageTitle = 'Tạo banner';
      $this->layout = '//layouts/cms/create';
      $this->render('create',array(
         'model' => $model,
         'message' => $message,
      ));
   }
   
   /**
    * Deactive record
   */
	public function actionDeactive(){
      $error = 1;
      $record_affected = 0;
      $list_id = Yii::app()->request->getParam('list_id',array());
      $session_user = Yii::app()->request->getParam('session_user','');
      if($session_user == Yii::app()->session['session_user'])
      {
         if(count($list_id) > 0){
            $sql = 'UPDATE banner SET ban_active = 0 WHERE ban_id IN(-1';
            foreach ($list_id as $item){
               if(is_numeric($item))
                  $sql .= ',' . $item;
            }
            $sql .= ')';
            $db = Yii::app()->db;
            $cmd = $db->createCommand($sql);
            $record_affected = $cmd->execute();
            if($record_affected >= 0){
               $error = 0;
            }else{
               $error = 1;
            }
         }
         
      }
      echo json_encode(array('error' => $error,
                             'record_affected' => $record_affected)); 
	}
   
   /**
    * Active record
   */
	public function actionActive(){
      $error = 1;
      $record_affected = 0;
      $list_id = Yii::app()->request->getParam('list_id',array());
      $session_user = Yii::app()->request->getParam('session_user','');
      if($session_user == Yii::app()->session['session_user'])
      {
         if(count($list_id) > 0){
            $sql = 'UPDATE banner SET ban_active = 1 WHERE ban_id IN(-1';
            foreach ($list_id as $item){
               if(is_numeric($item))
                  $sql .= ',' . $item;
            }
            $sql .= ')';
            $db = Yii::app()->db;
            $cmd = $db->createCommand($sql);
            $record_affected = $cmd->execute();
            if($record_affected >= 0){
               $error = 0;
            }else{
               $error = 1;
            }
         }
         
      }
      echo json_encode(array('error' => $error,
                             'record_affected' => $record_affected)); 
	}
   
   /**
    * Delete record
   */
	public function actionDelete(){
      $error = 1;
      $record_affected = 0;
      $list_id = Yii::app()->request->getParam('list_id',array());
      $session_user = Yii::app()->request->getParam('session_user','');
      if($session_user == Yii::app()->session['session_user'])
      {
         if(count($list_id) > 0){
            $sql = 'DELETE FROM baner WHERE ban_id IN(-1';
            foreach ($list_id as $item){
               if(is_numeric($item))
                  $sql .= ',' . $item;
            }
            $sql .= ')';
            $db = Yii::app()->db;
            $cmd = $db->createCommand($sql);
            $record_affected = $cmd->execute();
            if($record_affected >= 0){
               $error = 0;
            }else{
               $error = 1;
            }
         }
         
      }
      echo json_encode(array('error' => $error,
                             'record_affected' => $record_affected)); 
	}


	// Uncomment the following methods and override them if needed
	/*
	public function filters()
	{
		// return the filter configuration for this controller, e.g.:
		return array(
			'inlineFilterName',
			array(
				'class'=>'path.to.FilterClass',
				'propertyName'=>'propertyValue',
			),
		);
	}

	public function actions()
	{
		// return external action classes, e.g.:
		return array(
			'action1'=>'path.to.ActionClass',
			'action2'=>array(
				'class'=>'path.to.AnotherActionClass',
				'propertyName'=>'propertyValue',
			),
		);
	}
	*/
}